<template>
  <div class="calendar-filter">
    <el-form :inline="device === 'mobile' ? false : true" :model="filterData" class="demo-form-inline">
      <el-form-item v-if="showSearchKeyword" label="关键字">
        <el-input
          v-model="filterData.content"
          clearable
          size="small"
          placeholder="请输入"
          @keyup.enter.native="handleSubmit"
        ></el-input>
      </el-form-item>
      <el-form-item v-if="showYearPicker" label="年度">
        <el-date-picker
          v-model="filterData.year"
          :clearable="false"
          type="year"
          align="right"
          size="small"
          format="yyyy年"
          @change="handleSubmit"
          style="width: 110px"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item v-if="showDateTypeSelect" label="年度区间">
        <el-select
            v-model="filterData.dateType"
            size="small"
            @change="handleSubmit"
            placeholder="请选择"
            style="width: 100px"
          >
            <el-option label="上半年" value="上半年" />
            <el-option label="下半年" value="下半年" />
            <el-option label="全年" value="全年" />
          </el-select>
      </el-form-item>
      <el-form-item v-if="showReportSelect" label="汇报类型">
        <el-select
            v-model="filterData.reportType"
            size="small"
            @change="handleSubmit"
            placeholder="请选择"
            style="width: 134px"
          >
            <el-option label="个人" value="person" />
            <el-option label="单位" value="unit" />
            <el-option label="战役/重点工作" value="keyWork" />
          </el-select>
      </el-form-item>
      <el-form-item v-if="showHumanPart" label="人员部门">
        <treeselect
          v-model="filterData.user"
          :multiple="false"
          :options="deparmentTree"
          placeholder="请选择"
          @input="handleSubmit"
        />
      </el-form-item>
      <el-form-item v-if="showGroup" label="群组">
         <el-select
          v-model="filterData.group"
          multiple
          clearable
          size="small"
          placeholder="请选择"
          @change="handleSubmit"
        >
          <el-option
            v-for="({id, name}) in userGroupList"
            :key="id"
            :label="name"
            :value="id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="showDatePickerSingle" label="日期">
        <el-date-picker
          v-model="filterData.dateSingle"
          type="date"
          align="right"
          size="small"
          style="width: 100%"
          :clearable='false'
          @change="handleSubmit"
        />
      </el-form-item>
      <el-form-item v-if="showDatePicker" label="日期范围">
        <el-date-picker
          v-model="filterData.dateRange"
          type="daterange"
          align="right"
          size="small"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="handleSubmit"
          :picker-options="pickerOptions"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item v-if="showMonthPicker" label="月份范围">
        <el-date-picker
          v-model="filterData.monthRange"
          type="monthrange"
          align="right"
          size="small"
          format="yyyy年MM月"
          unlink-panels
          range-separator="至"
          start-placeholder="开始月份"
          end-placeholder="结束月份"
          @change="handleSubmit"
          :picker-options="monthPickerOptions"
          style="width: 100%"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item v-if="showRandomCheck" label="随机抽查">
        <el-switch 
          v-model="filterData.range_inspect" 
          :active-value="1" 
          :inactive-value="0"
          @change="handleSubmit"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="handleSubmit"
          >查询</el-button
        >
        <el-button size="small" @click="handleClear">重置</el-button>
        <el-button v-if="showExport" size="small" @click="onExport"
          >导出</el-button
        >
        <div class="backMain">
          <el-tooltip effect="dark" content="返回首页" placement="top-start">
            <img
              alt="回到首页"
              @click="backMain"
              align="bottom"
              src="../../../../assets/backMain.png"
              width="30px"
            />
          </el-tooltip>
            <div v-if="pendingTaskNum > 0" class="toggleNums">{{ pendingTaskNum }}+</div>
          <!-- <span>Home</span> -->
        </div>
        <el-dropdown
          v-if="showExportMenu"
          style="margin-left: 10px"
          @command="onExport"
        >
          <el-button size="small">
            导出<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="toPdf">生成pdf</el-dropdown-item>
            <el-dropdown-item command="toInfo">推送至公告通知</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <el-tooltip content="推送到周月报大屏" placement="top">
          <el-button v-if="showPushScreen" size="small" @click="onPushScreen">推送</el-button>
        </el-tooltip>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { mapGetters } from "vuex";

import moment from 'moment'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

import { getWeekDays } from "@/utils/index.js";

import { getUserDepartment, getShareGroupList } from "@/api/user.js";
import { TaskIng } from "@/api/workflow.js";

export default {
  name: "FilterForm",
  props: {
    onSubmit: {
      type: Function,
    },
    onClear: {
      type: Function,
    },
    onExport: {
      type: Function,
    },
    onPushScreen: {
      type: Function,
    },
    planType: {
      type: String
    },
    currentDay: {
      type: String
    },
    showSearchKeyword: {
      type: Boolean,
      default: true,
    },
    showDatePickerSingle:{
      type:Boolean,
      default:false
    },
    showDatePicker: {
      type: Boolean,
      default: false,
    },
    showMonthPicker: {
      type: Boolean,
      default: false,
    },
    showYearPicker: {
      type: Boolean,
      default: false,
    },
    showReportSelect: {
      type: Boolean,
      default: false,
    },
    showDateTypeSelect: {
      type: Boolean,
      default: false,
    },
    showExport: {
      type: Boolean,
      default: true,
    },
    showExportMenu: {
      type: Boolean,
      default: false,
    },
    showPushScreen: {
      type: Boolean,
      default: false,
    },
    showRandomCheck: {
      type: Boolean,
      default: false,
    },
    showHumanPart:{
      type: Boolean,
      default:true
    },
    showGroup:{
      type: Boolean,
      default:true
    }
  },
  components: {
    Treeselect,
  },
  computed: {
    ...mapGetters(["name", "roles", "id"]),
    device() {
      return this.$store.state.app.device;
    },
    pendingTaskNum() {
      return this.taskNum + this.approveNum
    }
  },
  watch: {
    currentDay: {
      handler(date) {
        const _currentDay = moment(date)
        const weekDays = getWeekDays(date)
        const startDate = weekDays[0]
        const endDate = weekDays[weekDays.length - 1]
        this.filterData = {
          ...this.filterData, 
          dateSingle:new Date(_currentDay),
          dateRange: [new Date(startDate), new Date(endDate)],
          monthRange: [_currentDay.startOf('month'), _currentDay.endOf('month')],
          year: _currentDay,
          dateType: '上半年',
          reportType: 'person'
        }
      },
      immediate: true
    }
  },
  data() {
    return {
      filterData: {},
      deparmentTree: [],
      userGroupList: [],
      usersID: [],
      taskNum: 0,
      approveNum: 0,
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      monthPickerOptions: {
        shortcuts: [
          {
            text: "本月",
            onClick(picker) {
              picker.$emit("pick", [new Date(), new Date()]);
            },
          },
          {
            text: "今年至今",
            onClick(picker) {
              const end = new Date();
              const start = new Date(new Date().getFullYear(), 0);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近六个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setMonth(start.getMonth() - 6);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },
  mounted() {
    this.requestDepartmentList();
    this.requestUserGroupList() // 请求人员群组
    this.fetchPendingTaskNum() // 请求代办任务数量
  },
  methods: {
    backMain() {
      this.$router.push({
        name: "HomePage",
      });
    },
    handleSubmit() {
      const { user, range_inspect } = this.filterData;
      const param = {};
      if (this.usersID.includes(user)) {
        param.userType = "user";
      } else {
        param.userType = "depart";
      }
      // 如果随机抽查关闭 默认不传
      if(!range_inspect) {
        param.range_inspect = undefined
      }
      this.onSubmit({ ...this.filterData, ...param });
    },
    handleClear() {
        const weekDays = getWeekDays(moment().format('YYYY-MM-DD'))
        const startDate = weekDays[0]
        const endDate = weekDays[weekDays.length - 1]
      this.filterData = {
        dateSingle:moment().format('YYYY-MM-DD'),
        dateRange:[new Date(startDate), new Date(endDate)],
      };
      // 重新请求数据
      this.onClear();
    },
    // 查询部门人员列表
    async requestDepartmentList() {
      const {data } = window.location.hash == '#/plann/yearly' 
      ?
      await getUserDepartment({ owner: this.id,location:'yearly' })
      :
      await getUserDepartment({ owner: this.id })
      const treeData = this.formatTreeDataSource(data);
      this.deparmentTree = treeData;
    },
    // 查询所有人员群组
    async requestUserGroupList() {
      const { data } = await getShareGroupList({ type: this.planType });
      this.userGroupList = data;
    },
    /**
     * 将树结构数据转换为目标字段
     * @param {*} arr
     * @returns
     */
    formatTreeDataSource(arr) {
      if (!Array.isArray(arr)) {
        return;
      }
      return arr.map((v, i) => {
        const { id, dt_name, user_department = [], child } = v;
        // 由于department和user为两张表，存在id相同的情况
        // 将所有user_deparment中的id设置为 u${id}
        const users =
          user_department &&
          user_department.map((item) => {
            const { id, first_name } = item;
            if (first_name) {
              this.usersID.push(`u${id}`);
            }
            return { id: `u${id}`, dt_name: first_name };
          });
        const _child = [...(child || []), ...users];
        const leafNode = {
          id,
          label: dt_name,
        };
        // 如果有_child有值，则添加children属性
        // 否则为叶子节点
        if (_child.length) {
          leafNode.children = _child ? this.formatTreeDataSource(_child) : "";
        }
        return leafNode;
      });
    },
    async fetchPendingTaskNum() {
      // 请求待办任务
      const { data: taskData } = await TaskIng(this.id, "TK")
      this.taskNum = taskData && taskData.count
      // 请求已办任务
      const { data: approveData } = await TaskIng(this.id, "SP")
      this.approveNum = approveData && approveData.count
    }
  },
};
</script>
<style lang="scss">
.calendar-filter {
  margin: 20px 20px 0;
  .backMain {
    margin-left: 15px;
    padding-top: 6px;
    float: right;
    cursor: pointer;
    margin-right: 8px;
    position: relative;
    span {
      font-size: 14px;
      font-weight: 700;
      color: #409eff;
    }
    .toggleNums {
      position: absolute;
      top: 2px;
      left: 31px;
      color: #e6e6e6;
      background: #f14c4c;
      padding: 0 4px;
      border-radius: 26px;
      height: 15px;
      min-width: 30px;
      text-align: center;
      font-size: 12px;
      line-height: 15px;
    }
  }
  .el-form-item {
    margin-bottom: 0;
  }

  .vue-treeselect {
    width: 200px;
    line-height: 30px;
    margin-top: 4px;

    .vue-treeselect__control {
      height: 33px;
    }
  }
  @media screen and (max-width: 500px){ 
    .vue-treeselect {
      width: 100%;
    }
  }
}
</style>
